package com.winning.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.winning.dao.CollectDao;
import com.winning.entity.RequestSet;
import com.winning.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.client.RestTemplate;


/**
 * 请求后结果集处理
 *
 * @author z_dd@winning.com.cn
 * @date 2019/1/25 10:47
 */
@Slf4j
@Service
public class ResultService {
    @Value("${com.winning.geturl.comprehensive}")
    String getUrl;

    @Autowired
    CollectDao collectDao;

    @Autowired
    RestTemplate restTemplate;

    /**
     * 具体处理方法, 数据单表存入数据库
     *
     * @param requestSet 具体请求参数
     * @author Administrator
     * @date 2019/1/25
     */
    @Transactional(rollbackFor = Exception.class)
    public void operation(RequestSet requestSet, String tableName) {
        try {
            String requestParam = JSON.toJSONString(requestSet, SerializerFeature.WriteMapNullValue);
            ResponseEntity<String> forEntity = restTemplate.getForEntity(getUrl + "?data={requestParam}", String.class, requestParam);
            int statusCodeValue = forEntity.getStatusCodeValue();
            if (200 == statusCodeValue) {
                String restStr = forEntity.getBody();
                log.info(restStr + "");
                JSONObject restJson = JSON.parseObject(restStr);

                if ("00000".equals(restJson.getString("code"))) {
                    JSONArray responseContent = restJson.getJSONArray("responseContent");
                    for (int i = 0; i < responseContent.size(); i++) {
                        //转换时间字符串格式
                        JSONObject jsonObject = DateUtil.formatJsonDate(responseContent.getJSONObject(i), "yyyy-MM-dd HH:mm:ss");

                        log.info(jsonObject + "");
                        collectDao.insertData(tableName, jsonObject);
                    }
                } else {
                    //接口放回自定义的非成功代码
                    log.warn("{} 接口请求,code:{},codeDesc:{}", tableName, restJson.getString("code"), restJson.getString("codeDesc"));
                }
            } else {
                log.error("RestTemplate请求错误,HTTP状态码: {}", statusCodeValue);
            }
        } catch (Exception e) {
            log.error("{} 接口请求异常,事务已回滚", tableName, e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void operation(RequestSet requestSet, String masterTableName, String slaveTableName) {
        try {
            String requestParam = JSON.toJSONString(requestSet, SerializerFeature.WriteMapNullValue);
            ResponseEntity<String> forEntity = restTemplate.getForEntity(getUrl + "?data={requestParam}", String.class, requestParam);

            int statusCodeValue = forEntity.getStatusCodeValue();

            if (200 == statusCodeValue) {
                String restStr = forEntity.getBody();
                log.info(restStr + "");
                JSONObject restJson = JSON.parseObject(restStr);

                if ("00000".equals(restJson.getString("code"))) {
                    JSONArray responseContent = restJson.getJSONArray("responseContent");

                    for (int i = 0; i < responseContent.size(); i++) {

                        JSONObject masterJson = responseContent.getJSONObject(i);
                        log.info(masterJson + "\n");
                        JSONArray items = (JSONArray) masterJson.remove("items");
                        collectDao.insertData(masterTableName, masterJson);
                        for (int j = 0; j < items.size(); j++) {
                            JSONObject slaveJson = items.getJSONObject(j);
                            collectDao.insertData(slaveTableName, slaveJson);
                        }

                    }
                } else {
                    //接口放回自定义的非成功代码
                    log.warn("{} 接口请求,code:{},codeDesc:{}", slaveTableName, restJson.getString("code"), restJson.getString("codeDesc"));
                }

            } else {
                log.error("RestTemplate请求错误,HTTP状态码: {}", statusCodeValue);
            }
        } catch (Exception e) {
            log.error("{} 接口请求异常,事务已回滚", slaveTableName, e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }


}
